package com.dms.modules.product.controller;

import com.dms.common.api.ApiResponse;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.product.service.ProductRecommendationService;
import com.dms.modules.product.vo.ProductDetailVO;
import com.dms.modules.product.vo.ExperimentGroupInfo;
import com.dms.modules.product.entity.ProductRecommendationExperiment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 商品推荐系统前端控制器
 * 权限说明：
 * - ROLE_USER: 普通用户角色，可以访问基础推荐功能
 * - ROLE_ADMIN: 管理员角色，可以访问所有功能
 */
@RestController
@RequestMapping("/api/v1/product/recommendation")
@Api(tags = "商品推荐管理")
public class ProductRecommendationController {

    @Autowired
    private ProductRecommendationService recommendationService;

    @ApiOperation("获取个性化推荐商品")
    @GetMapping("/personalized/{userId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<ProductDetailVO>> getPersonalizedRecommendations(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId,
            @ApiParam(value = "返回数量", defaultValue = "20") @RequestParam(defaultValue = "20") Integer limit) {
        return ApiResponse.success(recommendationService.getPersonalizedRecommendations(userId, limit));
    }

    @ApiOperation("获取相似商品推荐")
    @GetMapping("/similar/{productId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<ProductDetailVO>> getSimilarProducts(
            @ApiParam(value = "商品ID", required = true) @PathVariable Long productId,
            @ApiParam(value = "返回数量", defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit) {
        return ApiResponse.success(recommendationService.getSimilarProducts(productId, limit));
    }

    @ApiOperation("获取热门商品推荐")
    @GetMapping("/hot")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<ProductDetailVO>> getHotProducts(
            @ApiParam(value = "返回数量", defaultValue = "20") @RequestParam(defaultValue = "20") Integer limit) {
        return ApiResponse.success(recommendationService.getHotProducts(limit));
    }

    @ApiOperation("获取新品推荐")
    @GetMapping("/new")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<ProductDetailVO>> getNewProducts(
            @ApiParam(value = "返回数量", defaultValue = "20") @RequestParam(defaultValue = "20") Integer limit) {
        return ApiResponse.success(recommendationService.getNewProducts(limit));
    }

    @ApiOperation("获取基于浏览历史的推荐")
    @GetMapping("/browse-history/{userId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<ProductDetailVO>> getBrowseHistoryRecommendations(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId,
            @ApiParam(value = "返回数量", defaultValue = "20") @RequestParam(defaultValue = "20") Integer limit) {
        return ApiResponse.success(recommendationService.getBrowseHistoryRecommendations(userId, limit));
    }

    @ApiOperation("获取基于收藏的推荐")
    @GetMapping("/favorite/{userId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<ProductDetailVO>> getFavoriteRecommendations(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId,
            @ApiParam(value = "返回数量", defaultValue = "20") @RequestParam(defaultValue = "20") Integer limit) {
        return ApiResponse.success(recommendationService.getFavoriteRecommendations(userId, limit));
    }

    // =============== 实验组管理接口 ===============

    @ApiOperation("查询用户实验组信息")
    @PostMapping("/experiment/query")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Map<Long, ExperimentGroupInfo>> queryUserExperimentGroups(
            @ApiParam(value = "用户ID列表", required = true) @RequestBody List<Long> userIds) {
        return ApiResponse.success(recommendationService.queryUserExperimentGroups(userIds));
    }

    @ApiOperation("重新分配用户实验组")
    @PostMapping("/experiment/reassign/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<ExperimentGroupInfo> reassignUserExperimentGroup(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        return ApiResponse.success(recommendationService.reassignUserExperimentGroup(userId));
    }

    @ApiOperation("批量重置用户实验组")
    @PostMapping("/experiment/batch-reassign")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Integer> reassignUsersToGroup(
            @ApiParam(value = "用户ID列表", required = true) @RequestBody List<Long> userIds,
            @ApiParam(value = "目标实验组", required = true) @RequestParam String targetGroup) {
        return ApiResponse.success(recommendationService.reassignUsersToGroup(userIds, targetGroup));
    }

    @ApiOperation("获取所有活跃的实验配置")
    @GetMapping("/experiment/active")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<List<ProductRecommendationExperiment>> getActiveExperiments() {
        return ApiResponse.success(recommendationService.getActiveExperiments());
    }

    @ApiOperation("获取实验组用户统计")
    @GetMapping("/experiment/stats/user-counts")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Map<String, Long>> getExperimentGroupUserCounts() {
        return ApiResponse.success(recommendationService.getExperimentGroupUserCounts());
    }

    @ApiOperation("获取实验组效果指标统计")
    @GetMapping("/experiment/stats/metrics")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Map<String, Map<String, Object>>> getExperimentGroupMetrics(
            @ApiParam(value = "开始时间", required = true) 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @ApiParam(value = "结束时间", required = true) 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        return ApiResponse.success(recommendationService.getExperimentGroupMetrics(startTime, endTime));
    }

    @ApiOperation("获取用户推荐历史")
    @GetMapping("/history/{userId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<Map<String, Object>>> getUserRecommendationHistory(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId,
            @ApiParam(value = "开始时间", required = true) 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @ApiParam(value = "结束时间", required = true) 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        return ApiResponse.success(recommendationService.getUserRecommendationHistory(userId, startTime, endTime));
    }

    // =============== 用户行为记录接口 ===============

    @ApiOperation("记录用户点击")
    @PostMapping("/record/click")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<Void> recordUserClick(
            @ApiParam(value = "用户ID", required = true) @RequestParam Long userId,
            @ApiParam(value = "商品ID", required = true) @RequestParam Long productId) {
        recommendationService.recordUserClick(userId, productId);
        return ApiResponse.success();
    }

    @ApiOperation("记录用户浏览")
    @PostMapping("/record/view")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<Void> recordUserView(
            @ApiParam(value = "用户ID", required = true) @RequestParam Long userId,
            @ApiParam(value = "商品ID", required = true) @RequestParam Long productId) {
        recommendationService.recordUserView(userId, productId);
        return ApiResponse.success();
    }
} 